import "@leafer-in/editor";
import "@leafer-in/view";
import "@leafer-in/viewport"; // 导入视口插件(可选)
import "@leafer-in/resize";
import { onMounted, effect, Ref, nextTick } from "vue";
import { Rect, App } from "leafer-ui";
import { onUnmounted } from "vue";

export default function useScaleImg({ view, isInit, url }: { view: string; isInit: Ref<boolean>; url: Ref<string> }) {
  let app: App, rect: Rect;
  effect(() => {
    console.log("初始化 ", isInit.value);
    if (isInit.value && url.value) {
      nextTick(() => {
        init();
      });
    } else {
      destroy();
    }
    return () => {
      destroy();
    };
  });

  function init() {
    setTimeout(() => {
      app = new App({
        view: view,
        tree: {
          type: "document",
        },
        editor: {
          editSize: "scale",
          lockRatio: true,
          moveable: "move",
          resizeable: "zoom",
          rotateable: false,
        }, //  配置 editor 会自动创建并添加 app.editor 实例、tree 层、sky 层
      });

      rect = new Rect({
        x: 100,
        y: 100,
        width: 400,
        fill: {
          type: "image",
          // url: poster1,
          url: url.value,
        },
        draggable: true,
        editable: true,
      });
      app.tree.add(rect);
      app.tree.zoom("fit-width", 0, true);
    }, 500);
  }

  function destroy() {
    if (app) {
      app.destroy();
    }
    if (rect) {
      rect.destroy();
    }
  }
}
